package com.example.tabbar.utils

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tabbar.adapter.SpinnerAdapters


class CustomSpinner(
    private val context: Context,
    private val items: List<String>,
    private val onItemSelectedListener: (position: Int, item: String) -> Unit
) {
    private lateinit var popupWindow: PopupWindow
    private var selectedPosition = -1
    private var onDismissListener: (() -> Unit)? = null



    fun show(anchorView: View) {
        val recyclerView = RecyclerView(context)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.layoutParams = RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.MATCH_PARENT,
            RecyclerView.LayoutParams.WRAP_CONTENT
        )

//        val adapter = SpinnerAdapters(items) { position ->
//            selectedPosition = position
//            onItemSelectedListener(position, items[position])
//            popupWindow.dismiss()
//        }
        val adapter = SpinnerAdapters(items, object : SpinnerAdapters.OnItemClickListener {
            override fun onItemClick(position: Int) {
                selectedPosition = position
                onItemSelectedListener(position, items[position])
                popupWindow.dismiss()
            }
        })
        recyclerView.adapter = adapter

        popupWindow = PopupWindow(recyclerView, anchorView.width, 220, true)
        popupWindow.setBackgroundDrawable(ColorDrawable(Color.WHITE))
        popupWindow.elevation = 8f

        // 设置关闭监听器
        popupWindow.setOnDismissListener {
            onDismissListener?.invoke()
        }

        if (selectedPosition >= 0) {
            adapter.setSelectedPosition(selectedPosition)
        }

        popupWindow.showAsDropDown(anchorView, 0, 5)
    }

    fun setSelectedPosition(position: Int) {
        selectedPosition = position
    }

    // 添加设置关闭监听器的方法
    fun setOnDismissListener(listener: () -> Unit) {
        this.onDismissListener = listener
    }
}